using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MuscleFellow.API.Models;
using MuscleFellow.Data.Interfaces;
using MuscleFellow.Models;

namespace MuscleFellow.API.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    public class AccountController:Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly ICartItemRepository _cartItemRepository;
        private readonly ILogger _logger;
        private readonly IOptions<WebApiSetting> _setting;

        public AccountController(UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            ICartItemRepository cartItemRepository,
            ILogger logger,
            IOptions<WebApiSetting> setting )
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _cartItemRepository = cartItemRepository;
            _logger = logger;
            _setting = setting;
        }
        [HttpGet]
        [Authorize]
        public async Task<IActionResult> Get([FromQuery] string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return Ok();
            }
            var user = await _userManager.FindByIdAsync(id);
            var result = new JsonResult(user);
            return result;
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Register([FromBody] LoginApiModel registerModel)
        {
            var user = new ApplicationUser { UserName=registerModel.UserId,Email = registerModel.UserId};
            var result = await _userManager.CreateAsync(user,registerModel.Password);
            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, isPersistent: true);
                _logger.LogInformation(3,"User created a new account with password");
                return Ok();
            }
            return ResponseHelper.Unauthorized();
        }
        
    }

    public class ResponseHelper
    {
        public static IActionResult Unauthorized()
        {
            throw new System.NotImplementedException();
        }
    }
}